package com.android.lib.messenger

import android.app.Service
import android.content.Intent
import android.os.Handler
import android.os.IBinder
import android.os.Message
import android.os.Messenger
import com.android.lib.messenger.utils.Const
import java.util.concurrent.ConcurrentHashMap

class BinderServer : Service() {

    companion object {
        /**
         * 消息集合map
         */
        var messageMap: ConcurrentHashMap<Int, Messenger> = ConcurrentHashMap<Int, Messenger>()

        /**
         * MessengerService用ServiceHandler接收并处理来自于客户端的消息
         */
        var serviceHandler : Handler = ServiceHandler()

        /**
         * serviceMessenger是Service自身的Messenger，其内部指向了ServiceHandler的实例,
         * 客户端可以通过IBinder构建Service端的Messenger，从而向Service发送消息,
         * 并由ServiceHandler接收并处理来自于客户端的消息
         */
        var serviceMessenger : Messenger = Messenger(serviceHandler)

        private fun sendMsg(msg: Message) {
            for (messenger in messageMap.values) {
                //发送消息
                if (null != messenger) {
                    messenger.send(msg)
                }
            }
            MessageProcessor.onMessageReceive(msg.data)
        }

    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        if (null != intent && null != intent.extras) {
            val message: Message = Message.obtain(serviceHandler, Const.SEND_MSG_TO_TARGET)
            message.replyTo = serviceMessenger
            message.data = intent.extras
            sendMsg(message)
        }
        return START_NOT_STICKY
    }

    override fun onBind(intent: Intent?): IBinder? {
        //获取Service自身Messenger所对应的IBinder，并将其发送共享给所有客户端
        return serviceMessenger.binder
    }

    /**
     *  MessengerService用ServiceHandler接收并处理来自于客户端的消息
     */
    class ServiceHandler : Handler() {
        override fun handleMessage(msg: Message) {
            val what = msg.what
            val key = msg.arg1
            when (what) {
                Const.SUBSCRIBE -> messageMap[key] = msg.replyTo
                Const.SEND_MSG_TO_TARGET -> sendMsg(msg)  //要发送的消息
                Const.UNSUBSCRIBE -> messageMap.remove(key)
            }
        }
    }

}